<?php

namespace App\Http\Controllers\Admin\CMS;

use App\Http\Models\Admin\AdminUsers;
use App\Http\Models\Admin\CMS\Category;
use App\Http\Models\Admin\CMS\Post;
use App\Http\Models\Admin\CMS\PostExtends;
use App\Http\Models\Admin\CMS\PostHistory;
use App\Http\Models\Admin\CMS\PostPro;
use App\Http\Models\Admin\CMS\PostTags;
use App\Http\Models\Admin\CMS\Tag;
use App\Http\Responses\ResponseDto;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Input;
use DB;
class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        //
        return View::make('admin.cms.posts')->withUserinfo($request->session()->get('adminUser'))
            ->withUrltitle(trans("admin/message.posts_index"))
            ->withAssets($request['ASSETS']);
    }

    public function page(Request $request)
    {
        $datas = $request->input();
        $start = $datas[3]['value'];
        $length = $datas[4]['value'];

        $posts = DB::table('posts')->skip($start)->take($length)->get();
        $total = DB::table('posts')->count();
        if($posts){
            foreach($posts as $item){
                $item->post_content = null;
                $aduser = AdminUsers::find($item->auth_id);
                if($aduser){
                    $item->auth_name = $aduser->user_name;
                }
                $category = Category::find($item->category_id);
                if($category){
                    $item->category_name = $category->name;
                }
                $tags = DB::table('post_tags')
                    ->rightJoin('tags', 'post_tags.tag_id', '=', 'tags.id')
                    ->where('post_tags.post_id',$item->id)
                    ->get();
                $tagnames = array();
               if($tags){
                   foreach($tags as $tag){
                       $tagnames[]=$tag->name;
                   }
                   $item->tag_names =implode(',',$tagnames);
               }
            }
        }
        return ResponseDto::createResObj(ResponseDto::convertPageToDataTableObj($posts,$total),ResponseDto::$SUCCESS);
    }


    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {

        $post = null;
        if($request->input('id')){

            if($request->input('history')){
                $post = PostHistory::where('id', $request->input('history'))->first();
                if($post){
                    $post->id = $post->post_id;
                    $post->history=$request->input('history');
                }
            }else{
                $post = Post::where('id', $request->input('id'))->first();
            }

            if($post){
                $category = Category::find($post->category_id);
                if($category){
                    $post->category_name = $category->name;
                }

                $auth = $request->session()->get('adminUser');
                $post->auth_name = $auth->user_name;
                $tags = PostTags::where('post_id',$post->id)->get();
                if($post->post_attribute){
                    $post->attribute = unserialize($post->post_attribute);
                }

                $tagids = array();
                foreach($tags as $tem){
                    $tagids[]=$tem->tag_id;
                }

                if(count($tagids) > 0){
                    $post->category_tags = implode(",",$tagids);
                }

                $post->historylist = PostHistory::select('id','created_at','title')->where('post_id',$request->input('id'))->orderBy('created_at',"desc")->get();
            }



        }
        $result = View::make('admin.cms.post_edit')->withUserinfo($request->session()->get('adminUser'))
            ->withUrltitle(trans("admin/message.posts_edit"))
            ->withAssets($request['ASSETS'])
            ->withPostpros(PostPro::orderBy('show_index','asc')->get());
        if($post){
            $result ->withPost($post);
        }
        return $result;
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make(Input::all(),
            [
                'title' => 'required',
            ]);
        if($validator->fails()){
            return ResponseDto::createResObj($validator->errors()->first(),ResponseDto::$FAIL);
        }else{

            $auth = $request->session()->get('adminUser');

            $post = new Post();
            $post_history = new PostHistory();
            $post_history->title = $post->title = $request->input("title");
            $post_history->post_content = $post->post_content = $request->input("post_content");
            if($post->post_content) {
                preg_match('/<img.+src=\"?(.+\.(jpg|gif|bmp|bnp|png))\"?.+>/i',$post->post_content,$match);
                if(count($match)>0){
                    $post_history->load_img = $post->load_img = $match[1];
                }else {
                    $post_history->load_img = $post->load_img = null;
                }
            }else{
                $post_history->load_img = $post->load_img = null;
            }




            $post_history->post_status = $post->post_status = $request->input("post_status");
            if($request->input("category_id") != null ){
                $post_history->category_id = $post->category_id = $request->input("category_id");
            }
            $post_history->auth_id = $post->auth_id = $auth->id;
            $post_history->use_seo = $post->use_seo = $request->input("use_seo");
            $post_history->seo_title = $post->seo_title = $request->input("seo_title");
            $post_history->seo_keywords = $post->seo_keywords = $request->input("seo_keywords");
            $post_history->seo_description = $post->seo_description = $request->input("seo_description");
            $post_history->seo_meta = $post->seo_meta = $request->input("seo_meta");


            $post_history->post_attribute = $post->post_attribute = PostPro::getConvertPro($request);

            $tags = $request->input("category_tags");

            if($request->input("id")){
                //更新操作
                $exit_item = Post::where('id','<>',$request->input("id"))->where('title',$post->title)->first();
                if($exit_item){
                    return ResponseDto::createResObj(trans("admin/message.name_exit"),ResponseDto::$FAIL);
                }
                else{
                    $up_item = Post::find($request->input("id"));
                    $up_item->title = $post->title;
                    $up_item->post_content = $post->post_content;
                    $up_item->post_status = $post->post_status;
                    $up_item->category_id = $post->category_id;
                    $up_item->auth_id = $post->auth_id;

                    $up_item->load_img = $post->load_img;
                    $up_item->use_seo = $post->use_seo;
                    $up_item->seo_title = $post->seo_title;
                    $up_item->seo_keywords = $post->seo_keywords;
                    $up_item->seo_description = $post->seo_description;
                    $up_item->seo_meta = $post->seo_meta;
                    $up_item->post_attribute = $post->post_attribute;
                    $up_item->save();

                    //更新标签.tag
                    $this->updatePostTags($up_item->id,$tags);

                    //保存备份
                    $post_history->post_id = $up_item->id;
                    $post_history->save();
                    return ResponseDto::createResObj(trans("admin/message.update_success"),ResponseDto::$SUCCESS);
                }
            }
            else{
                //添加操作
                $find = Post::where('title',$request->input("title"))->first();
                if($find){
                    return ResponseDto::createResObj(trans("admin/message.name_exit"),ResponseDto::$FAIL);
                }
                if($post->save()){
                    $post = Post::where('title',$post->title)->first();
                    $this->updatePostTags($post->id,$tags);

                    //保存备份
                    $post_history->post_id = $post->id;
                    $post_history->save();
                }

                return ResponseDto::createResObj(trans("admin/message.submit_success"),ResponseDto::$SUCCESS);
            }




        }
    }
    public function updatePostTags($postid,$tags)
    {
        //填写标签类信息
//        $post = Post::where('title',$post->title)->first();
        PostTags::where('post_id',$postid)->delete();
        if($tags){
            foreach($tags as $tag){
                $ftag = Tag::find($tag);
                if($ftag == null){
                    $savetag = new Tag();
                    $savetag->name = $tag;
                    $savetag->save();
                    $ftag = Tag::where('name',$tag)->first();
                }
                $ptg= new PostTags();
                $ptg->post_id =$postid;
                $ptg->tag_id = $ftag->id;
                $ptg->save();
            }
        }

    }


    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show(Request $request,$id)
    {

    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Request $request,$id)
    {


    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
        Post::destroy($id);
        PostTags::where('post_id',$id)->delete();
        return ResponseDto::createResObj(trans("admin/message.update_success"),ResponseDto::$SUCCESS);
    }
    public function deletePostHistory()
    {
        //

        PostHistory::destroy(request()->input("id"));

        return ResponseDto::createResObj(trans("admin/message.update_success"),ResponseDto::$SUCCESS);
    }
}
